package com.cloud.bssp.thread.sync.readwritelock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @description： 数据容器类
 * @author：weirx
 * @date：2022/1/13 15:29
 * @version：3.0
 */
public class DataContainer {

    /**
     * 初始化读锁和写锁
     */
    private ReentrantReadWriteLock reentrantReadWriteLock = new ReentrantReadWriteLock();
    private ReentrantReadWriteLock.ReadLock readLock = reentrantReadWriteLock.readLock();
    private ReentrantReadWriteLock.WriteLock writeLock = reentrantReadWriteLock.writeLock();

    protected void read(){
        readLock.lock();
        try {
            System.out.println("获取读锁");
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            readLock.unlock();
            System.out.println("释放读锁");
        }
    }

    protected void write(){
        writeLock.lock();
        try {
            System.out.println("获取写锁");
            TimeUnit.SECONDS.sleep(1);
            System.out.println("获取读锁");
            readLock.lock();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            writeLock.unlock();
            System.out.println("释放写锁");
        }
    }
}
